<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="房间" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="房间ID" prop="houseId">-->
<!--        <el-input-->
<!--          v-model="queryParams.houseId"-->
<!--          placeholder="请输入"-->
<!--          clearable-->
<!--          style="width: 240px"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="地区" prop="estateName">
        <!-- <el-input
          v-model="queryParams.estateName"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        /> -->
        <el-cascader
            ref="areaPicker"
            v-model="queryParams.region"
            :props="areaProps"
            :show-all-levels="true"
            @change="handleChangeArea"
            clearable
            placeholder="请选择"
            style="width: 240px"
          ></el-cascader>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-radio-group v-model="current" @change="stateHandel">
        <el-radio-button
          :label="index"
          v-for="(item, index) in statistics"
          :key="index"
        >{{ item.label }}（{{ item.number }}）
        </el-radio-button
        >
      </el-radio-group>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column label="房间" prop="" :show-overflow-tooltip="true" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.house.premisesAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="地区"
        prop="attractionsFullNames"
        :show-overflow-tooltip="true"
        width="400"
      >
        <template #default="scope">
          <span>{{ scope.row.house.provinceName }} {{ scope.row.house.cityName }} {{ scope.row.house.districtName }} {{scope.row.house.streetName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="床数" prop="bedNumber" align="center" width="80"></el-table-column>
      <el-table-column label="可住人数" prop="checkInNumber" align="center" width="80"/>
      <el-table-column label="配置状态" prop="editStatus" align="center" width="80">
        <template slot-scope="scope">
          {{ scope.row.allocationState == 0 ? "已配置" : "未配置" }}
        </template>
      </el-table-column>
      <el-table-column label="房源介绍" prop="apartmentDescription" align="center" show-overflow-tooltip/>
      <el-table-column label="上下架" prop="apartmentState" align="center" fixed="right" width="100px">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.apartmentState"
            active-value="0"
            inactive-value="1"
            @change="handleUnmountStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['enterprise:allocation:edit']"
          >配置
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <Edit v-model="open" v-if="open" :title="title" :houseId="id" @success="handleQuery"/>
    <!-- 详情弹出层 -->
  </div>
</template>

<script>
import {delRole, addRole, updateRole, dataScope} from "@/api/system/role";
import {
  listHousingAllocation,
  countByState,
  listPayType,
  changeApartmentStateStatus,
  allocationList,
} from "@/api/house/unmount";
import {treeselect as menuTreeselect} from "@/api/system/menu";

import Edit from "./components/edit.vue";
import Detail from "./components/detail.vue";
import { listArea } from "@/api/system/config";
import Template from '@/views/long-short-rent/contract/template/index.vue'

export default {
  name: "Unmount",
  dicts: [],
  components: {
    Template,
    Edit,
    Detail,
  },
  data() {
    return {
      //统计数据
      statistics: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //表格行id
      id: undefined,
      // 是否显示详情弹出层
      detailDialogVisible: false,
      // 当前选择
      current: "0",
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        apartmentType: undefined,
        editStatus: undefined,
        apartmentState: "",
        updateBy: undefined,
        'house.estateId':undefined,
        'house.buildingId':undefined,
        'house.provinceId':undefined,
        'house.cityId':undefined,
        'house.districtId':undefined,
        'house.streetId':undefined,
        'house.communityId':undefined,
      },
      // 表单参数
      form: {},
      payTypeList: [],
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 2,
              }));
              resolve(areas);
            }
          );
        },
      },
    };
  },
  filters: {
    payType(value, list, type) {
      if (type == 1) return "-";
      let result = list.find((item) => {
        return item.id == value;
      });
      return result ? result.name : value;
    },
  },
  computed: {
    generateRoom() {
      return (row) => {
        let name = "";
        if (row.estateName) name += row.estateName;
        if (row.buildingName) name += row.buildingName + "栋";
        if (row.unitName) name += row.unitName + "单元";
        if (row.roomNumber) name += row.roomNumber + "号";
        return name;
      };
    },
    generateAddress() {
      return (row) => {
        let name = "";
        if (row.provinceName) name += row.provinceName;
        if (row.cityName) name += row.cityName;
        if (row.districtName) name += row.districtName;
        if (row.streetName) name += row.streetName;
        return name;
      };
    },
  },
  created() {
    this.getList();
    this.getHousingAllocationStatistics();
    this.getPayType();
  },
  methods: {
    stateHandel(i) {
      delete this.queryParams["apartmentState"];
      delete this.queryParams["allocationState"];
      let value = this.statistics[i].value;
      let type = this.statistics[i].type;
      this.queryParams[type] = value;
      this.handleQuery();
    },
    //获取统计信息
    getHousingAllocationStatistics() {
      countByState().then((response) => {
        this.statistics = response.data;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      allocationList(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getHousingAllocationStatistics();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.houseId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加角色";
    },
    handleUpdate(row) {
      this.id = row.houseId;
      this.title = "配置";
      this.open = true;
    },
    handleDetail(row) {
      this.id = row.houseId;
      this.title = "详情";
      this.detailDialogVisible = true;
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.roleId != undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function () {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId || this.ids;
      this.$modal
        .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？')
        .then(function () {
          return delRole(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/enterprise/house/housingAllocation/export",
        {
          ...this.queryParams,
          houseIds: this.ids,
        },
        `房屋配置信息_${new Date().getTime()}.xlsx`
      );
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection();
    },
    //获取押付方式
    getPayType() {
      listPayType().then((response) => {
        this.payTypeList = response.data;
      });
    },
    //修改上下架状态
    handleUnmountStatusChange(row) {
      console.log("apartmentState", row.apartmentState);
      let text = row.apartmentState === "0" ? "上架" : "下架";
      this.$modal
        .confirm('确认要"' + text + '""' + row.houseId + '"房屋配置吗？')
        .then(function () {
          return changeApartmentStateStatus(row.allocationId);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        })
        .catch(function () {
          console.log("err");
          row.apartmentState = row.apartmentState === "1" ? "0" : "1";
        });
    },
    //区域选择
    handleChangeArea(val) {
      const checkedNode = this.$refs["areaPicker"].panel.getNodeByValue(val);
      const ids = checkedNode.path;
      const labels = checkedNode.pathLabels;

      this.queryParams['house.provinceId'] = ids[0];
      this.queryParams['house.cityId'] = ids[1];
      this.queryParams['hosue.districtId'] = ids[2];
      // this.queryParams.streetId = ids[3];
      // this.queryParams.communityId = ids[4];
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

.total {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
